#!/bin/bash
# Author : Raman Rawat
# Usage
# Copy files given in input file while maintaining the original directory structure.
# ./$0.sh -file file -dest tgtDir 

Usage()
{
echo "Usage :"
echo $0 " -file file -dest tgtDir "
echo "Copy files given in input file while maintaining the original directory structure."
echo " file == File containing one file entry with absolute path per line"
echo " tgtDir == Target directory to copy without ending /"

exit 1
}

# if number of args are less than 4 exit
if [ $# -lt 4 ] ; then
echo " Missing arguments:" 
Usage
fi

while [ $# -gt 0 ]; do    # Until you run out of parameters . . .
  case "$1" in
    -dest)
              # "-dest" parameter?
              tmpDir="$2"
              shift
              echo "Destination dir : "$tmpDir
              ;;
    -file)
              CONFFILE="$2"
              shift
              if [ ! -f $CONFFILE ]; then
                echo "Error: Supplied file doesn't exist!"
                exit $E_CONFFILE     # File not found error.
              fi
              echo " Reading config file" $CONFFILE
              ;;
  esac
  shift       # Check next set of parameters.
done

# CurrentWorkingDir
cwd=$PWD

# Function to create dir and parent dir if it doesn't exist
# $1 - Dir to create
CreateDir()
{
if [ ! -d $1 ] ; then
	mkdir -p $1
	echo "Creating directory" $1
fi
}

# Create a tmp dir where files will be copied.
#tmpDir=tmp
if [ -d  $tmpDir ] ; then 
	rm -rf $tmpDir
fi

CreateDir $tmpDir

i=0
# For each line in the file
for ln in `cat $CONFFILE` ; do 

	#i=`expr $i + 1` 
	let i=i+1
	echo $i ":" $ln 
	parentDir=`dirname $ln`
	
	mkdir -p $tmpDir/$parentDir
	# Create a single line file
	echo `basename $ln`  > $tmpDir/$ln
done

# find . -type f -exec wc -l {} \; | awk ' BEGIN {sum=0} { sum += $1} END { print sum}'

# find . -type f -exec wc -l {} \; | awk ' BEGIN {printf "%-20s %-15s","LINES"; sum=0} { print $0 ; sum += $1} END { print sum}'

# wc * | awk '{printf "%-20s %-15s %-15s\n","File"NR"=" $4,"lines="$1,"words="$2}'